import { useMessage } from '@hooks/useAppMessage'
import { useNavigate } from '@tanstack/react-router'
/**
 *
 * @param {Function} mutate
 * @param {Object} options
 * @param {(object:T) => T} options.handle - 处理函数，用于处理表单数据
 * @return {Object} {onFinish, onFailed}
 */
export function useFormCallback(mutate, options = {}) {
  const message = useMessage()
  const link = useNavigate()

  const { handle, onSuccess } = options

  const onFinish = (values) => {
    const data = handle ? handle(values) : values
    console.log('%c Line:16 🌽 useFormCallback handleData', 'color:#ffdd4d', data)
    mutate(data, {
      onSuccess: (res) => {
        console.log(data, res)
        onSuccess ? onSuccess(res.data) : link({ to: '..' })
      },
      onError: (error) => {
        console.error(error)
        message.error(error.message)
      },
    })
  }

  const onFailed = (error, cb) => {
    console.log('%c Line:32 🥑 error', 'color:#ea7e5c', error)
    const [{ errors }] = error.errorFields
    message.error(errors.join('、'))
    cb?.()
  }

  return {
    onFinish,
    onFailed,
  }
}
